<script lang="ts" setup>
import usePlayAudio from '@/hooks/usePlayAudio';

interface IProps {
  orderInfo: IOrderDetailInfo;
}

interface IState {
  extraInformationSet: Array<{ name: string; list: IGoodsAdditionalInfo[] }>;
}

const props = defineProps<IProps>();
const state = reactive<IState>({ extraInformationSet: [] });
const { isPlaying, playAudio, stopAudio } = usePlayAudio();

onMounted(() => {
  Object.keys(props.orderInfo.orderAttrs).forEach((key) => {
    if (key === '0') {
      state.extraInformationSet.push({ name: '额外信息', list: props.orderInfo.orderAttrs[key] as IGoodsAdditionalInfo[] });
    } else {
      state.extraInformationSet.push({ name: props.orderInfo.goodsList.find((item) => String(item.goodsId) === key)?.name + '- 额外信息' || '', list: props.orderInfo.orderAttrs[key] as IGoodsAdditionalInfo[] });
    }
  });
});

onUnmounted(() => {
  stopAudio;
});

// 处理图片预览
const handlePreviewImg = (index: number, urls: string[]) => {
  uni.previewImage({ urls, current: index });
};

// 语音播放控制
const handleVoicePlayControl = (url: string) => {
  if (isPlaying.value) {
    stopAudio();
  } else {
    playAudio(url);
  }
};
</script>

<template>
  <view class="mb-12px bg-white c-br" v-for="(group, groupIndex) in state.extraInformationSet" :key="groupIndex">
    <view class="fw-bold c-pd pb-0">{{ group.name }}</view>
    <van-divider />
    <van-cell :title="item.attrName" v-for="(item, index) in group.list" :key="index">
      <view v-if="item.fieldType === 2">
        {{ JSON.parse(item.fieldOptions).find((findItem: any) => item.value === findItem.id.toString()).name }}
      </view>
      <view v-else-if="item.fieldType === 6 && item.value">
        {{
          JSON.parse(item.fieldOptions)
            .map((i: any) => {
              return { id: i.id || i, name: i.name || i };
            })
            .find((findItem: any) => item.value === findItem.id.toString()).name
        }}
      </view>
      <view class="flex w-full overflow-scroll justify-end" v-else-if="item.fieldType === 4">
        <image class="w-20 h-20 mr-2 flex-shrink-0 c-br" v-for="(url, urlIndex) in item.value.split(',')" :key="urlIndex" mode="aspectFill" :src="url" @click="handlePreviewImg(urlIndex, item.value.split(','))" />
      </view>
      <view class="flex justify-end" v-else-if="item.fieldType === 5">
        <video class="w-20 h-20 c-br" :src="item.value" />
      </view>
      <view v-else-if="item.fieldType === 8">
        <van-button icon="volume-o" type="primary" size="mini" @click="handleVoicePlayControl(item.value)">{{ isPlaying ? '停止' : '播放' }}</van-button>
      </view>
      <view v-else>
        {{ item.value }}
      </view>
    </van-cell>
  </view>
</template>
